
import pymysql as ps

class MysqlHelpe:
   def __init__(self, host, user, password, database, charset):
       self.host = host
       self.user = user
       self.password = password
       self.database = database
       self.charset = charset
       self.db = None
       self.curs = None
   # 数据库连接
   def open(self):
       self.db = ps.connect(host=self.host, user=self.user, password=self.password,database=self.database, charset=self.charset)
       self.curs = self.db.cursor()
   # 数据库关闭
   def close(self):
       self.curs.close()
       self.db.close()



   # 数据增删改
   #"INSERT INTO image(imagedata,name) VALUES('%s','%s')" 插入语句
   #"delete from image where Id=%d"
   def cud(self, sql, params):
       self.open()
       try:
           self.curs.execute(sql%params)

           self.db.commit()
           print("ok_更改成功")
       except :
           print('cud出现错误')
           self.db.rollback()
       self.close()
   #只录入sql语句，不带参数的
   def cud_1(self, sql):
       self.open()
       try:
           self.curs.execute(sql)
           result = self.curs.fetchone()

           self.db.commit()
           return result
           print("ok_更改成功")
       except :
           print('cud出现错')
           self.db.rollback()
       self.close()
   # 数据查询
   def find(self, sql, params):
       self.open()
       try:
           result = self.curs.execute(sql%params)
           result = self.curs.fetchone()

           print("ok_查询成功")
           # print(result)
           return result
       except:
           print('find出现错误')
       self.close()
       # 数据查询,无参数
   def find_1(self, sql):
       self.open()
       try:
           result = self.curs.execute(sql)
           result = self.curs.fetchall()

           print("ok_查询成功")

           return result
       except:
           print('find出现错误')
       self.close()



sql1="INSERT INTO student(tel,name,id) VALUES('%s','%s','%d')"  #插入（增加）
sql2="DELETE from student WHERE  id='%s'"#删除
sql3="update student set tel='%s' where id= '%d'"#更改
sql4="select * from student where id ='%d'"#查
# db.cud(sql1,("15680873993","zhaolingling",4))
# db.cud(sql3,('110',1))

